<template>
  <div class="chart-card" style="grid-column: span 4;">
    <h2><i class="icon-chart-bar"></i> 中国人体质类型分布</h2>
    <div ref="populationChart" class="chart-container"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'PopulationChart',
  props: {
    wangQiTypes: {
      type: Array,
      required: true
    }
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    initChart() {
      const chart = echarts.init(this.$refs.populationChart);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}% ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: this.wangQiTypes.map(item => item.name)
        },
        series: [
          {
            name: '体质分布',
            type: 'pie',
            radius: ['30%', '70%'],
            center: ['40%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}%'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            data: this.wangQiTypes.map(item => ({
              value: item.percentage,
              name: item.name,
              itemStyle: {
                color: this.getConstitutionColor(item.name)
              }
            }))
          }
        ]
      };
      chart.setOption(option);
    },
    handleResize() {
      this.$nextTick(() => {
        echarts.getInstanceByDom(this.$refs.populationChart)?.resize();
      });
    },
    getConstitutionColor(name) {
      const colors = {
        '平和质': '#4CAF50',
        '气虚质': '#8BC34A',
        '阳虚质': '#00BCD4',
        '阴虚质': '#E91E63',
        '痰湿质': '#795548',
        '湿热质': '#FF5722',
        '血瘀质': '#9C27B0',
        '气郁质': '#3F51B5',
        '特禀质': '#607D8B'
      };
      return colors[name] || '#999';
    }
  }
};
</script>

<style scoped>
.chart-container {
  height: 280px;
}
</style>